package system

import (
	"strings"

	"github.com/micro-plat/hydra"
	"github.com/micro-plat/hydra/components"
	"github.com/micro-plat/lib4go/errs"
	"github.com/micro-plat/lib4go/types"
)

//QueryHandle  获取功能菜单列表数据
func (u *SystemMenuHandler) ListHandle(ctx hydra.IContext) (r interface{}) {

	ctx.Log().Info("--------获取功能菜单数据列表--------")
	ctx.Log().Info("1.检查必须字段")
	if err := ctx.Request().Check("ident"); err != nil {
		return err
	}

	ctx.Log().Info("2.查询数据")
	data, err := u.queryByIdent(ctx.Request().GetString("ident"))
	if err != nil {
		return err
	}
	return sortMenus(data)
}

//QueryHandle  获取功能菜单列表数据
func (u *SystemMenuHandler) ListBySysHandle(ctx hydra.IContext) (r interface{}) {

	ctx.Log().Info("--------获取功能菜单数据列表--------")
	ctx.Log().Info("1.检查必须字段")
	if err := ctx.Request().Check("sys_id"); err != nil {
		return err
	}

	ctx.Log().Info("2.查询数据")
	data, err := u.queryBySysID(ctx.Request().GetString("sys_id"))
	if err != nil {
		return err
	}
	return sortMenus(data)
}

//QueryHandle  获取功能菜单列表数据
func (u *SystemMenuHandler) ListByRoleHandle(ctx hydra.IContext) (r interface{}) {

	ctx.Log().Info("--------获取功能菜单数据列表--------")
	ctx.Log().Info("1.检查必须字段")
	if err := ctx.Request().Check("sys_id", "role_id"); err != nil {
		return err
	}

	ctx.Log().Info("2.查询数据")
	data, err := u.queryByRoleID(ctx.Request().GetString("sys_id"),
		ctx.Request().GetString("role_id"))
	if err != nil {
		return err
	}
	return data
}

//QueryHandle  获取功能菜单列表数据
func (u *SystemMenuHandler) SaveMenuByRoleHandle(ctx hydra.IContext) (r interface{}) {

	ctx.Log().Info("--------获取功能菜单数据列表--------")
	ctx.Log().Info("1.检查必须字段")
	if err := ctx.Request().Check("role_id", "sys_id", "ids"); err != nil {
		return err
	}

	ctx.Log().Info("2.批量删除数据")
	xdb, err := hydra.C.DB().GetRegularDB().Begin()
	if err != nil {
		return err
	}
	_, err = xdb.Execute(deleteRoleMenuByRole, map[string]interface{}{
		"role_id": ctx.Request().GetString("role_id"),
		"sys_id":  ctx.Request().GetString("sys_id"),
	})
	if err != nil {
		xdb.Rollback()
		return errs.NewErrorf(999, "删除角色菜单失败：%w", err)
	}

	ctx.Log().Info("3.批量添加数据")
	idlist := strings.Split(ctx.Request().GetString("ids"), ",")
	for _, v := range idlist {
		i, err := xdb.Execute(insertRoleMenuByRole, map[string]interface{}{
			"role_id": ctx.Request().GetString("role_id"),
			"sys_id":  ctx.Request().GetString("sys_id"),
			"id":      v,
		})
		if err != nil || i == 0 {
			xdb.Rollback()
			return errs.NewErrorf(999, "添加角色菜单失败：%w", errs.GetDBError(i, err))
		}
	}
	xdb.Commit()

	return "success"
}

//Query 获取用户指定系统的菜单信息
func (u *SystemMenuHandler) queryByIdent(ident string) (types.XMaps, error) {
	db := components.Def.DB().GetRegularDB()
	return db.Query(queryMenusByIdent, map[string]interface{}{
		"ident": ident,
	})
}

//Query 获取用户指定系统的菜单信息
func (u *SystemMenuHandler) queryBySysID(sys_id string) (types.XMaps, error) {
	db := components.Def.DB().GetRegularDB()
	return db.Query(queryMenusBySysID, map[string]interface{}{
		"id": sys_id,
	})
}

//Query 获取用户指定系统的菜单信息
func (u *SystemMenuHandler) queryByRoleID(sys_id string, role_id string) (types.XMaps, error) {
	db := components.Def.DB().GetRegularDB()
	return db.Query(queryMenuByRoleID, map[string]interface{}{
		"id":      sys_id,
		"role_id": role_id,
	})
}

//处理数据排序
func sortMenus(data types.XMaps) []map[string]interface{} {
	result := make([]map[string]interface{}, 0, 4)
	for _, row1 := range data {
		if row1.GetInt("parent") == 0 && row1.GetInt("level_id") == 1 {
			children1 := make([]map[string]interface{}, 0, 4)
			for _, row2 := range data {
				if row2.GetInt("parent") == row1.GetInt("id") && row2.GetInt("level_id") == 2 {
					children2 := make([]map[string]interface{}, 0, 8)
					for _, row3 := range data {
						if row3.GetInt("parent") == row2.GetInt("id") && row3.GetInt("level_id") == 3 {
							// delete(row3, "level_id")
							delete(row3, "parent")
							children2 = append(children2, row3)
						}
					}
					// delete(row2, "level_id")
					delete(row2, "parent")
					children1 = append(children1, row2)
					row2["children"] = children2
				}
			}
			// delete(row1, "level_id")
			delete(row1, "parent")
			row1["children"] = children1
			result = append(result, row1)
		}
	}
	return result
}
